package controllers

import (
	"crypto/md5"
	"encoding/hex"
	"github.com/astaxie/beego"
	"github.com/go-redis/redis"
	"github.com/sony/sonyflake"
	"help/lib"
)

type ShortController struct {
	beego.Controller
}


type Json struct {
	LongUrl  string `json:"long_url"`
	ShortUrl string `json:"short_url"`
	id       string `json:"id"`
}


func (c *ShortController) Post(){
	client := redis.NewClient(&redis.Options{
		Network:            "tcp",
		Addr:               "127.0.0.1:6379",
		Dialer:             nil,
		OnConnect:          nil,
		Password:           "",
		DB:                 1,
		MaxRetries:         0,
		MinRetryBackoff:    0,
		MaxRetryBackoff:    0,
		DialTimeout:        0,
		ReadTimeout:        0,
		WriteTimeout:       0,
		PoolSize:           0,
		MinIdleConns:       0,
		MaxConnAge:         0,
		PoolTimeout:        0,
		IdleTimeout:        0,
		IdleCheckFrequency: 0,
		TLSConfig:          nil,
	})

	_, err := client.Ping().Result()
	if err != nil {
		showRs(c,"redis error")
	}
	url := c.GetString("url")

	h := md5.New()
	h.Write([]byte(url))
	md5str := hex.EncodeToString(h.Sum(nil))
	ba62,err := client.HGet("md5",md5str).Result()
	if ba62!="" {
		showRs(c,ba62)
	}
	//id
	flake := sonyflake.NewSonyflake(sonyflake.Settings{})
	id, err := flake.NextID()
	if err != nil {
		showRs(c,"id error")
	}

	b62 := lib.Encode(int(id))
	_, err = client.HSet("data",b62,url).Result()

	if err != nil {
		showRs(c,"data error")
	}

	_,err = client.HSet("md5",md5str,b62).Result()
	if err != nil {
		showRs(c,"md5 set error")
	}

	_,err = client.HIncrBy("zid","id",1).Result()
	if err != nil {
		showRs(c,"HIncrBy error")
	}

	showRs(c,b62)

}

func showRs(c * ShortController,data string){
	c.Data["json"] = map[string]interface{}{"data":data,"code":0}
	c.ServeJSON()
	c.StopRun()
}



